import sys
import os
import re
import ConfigParser
import globalvar
import logging
from optparse import OptionParser

import fs_diff
import kernel_diff
import upk_gen
import upc_gen

import zipfile
import glob, os
import datetime
import scomo_gen

def main(*argv):
    """Generate the dm package using the """
    if argv:
        argv = list(argv)
    else:
        argv = sys.argv[1:]
        
    usage = "usage: dm -s raw_srouce -t raw_target -o fs_source -n fs_target -r target_version -v VENDOR"
    
    if(len(argv) == 0):
        print usage     
        exit(-1)
        
    parser = OptionParser(usage=usage)      

    parser.add_option("-s", "--rawsource", dest="rawsource",type="string",help="rawsource old version ")
    parser.add_option("-t", "--rawtarget", dest="rawtarget",type="string",help="rawtarget new version ")
    parser.add_option("-o", "--fssource", dest="fssource",type="string",help="fssource old version ")
    parser.add_option("-n", "--fstarget", dest="fstarget",type="string",help="fstarget old version ")
    parser.add_option("-r", "--newversionstr", dest="newversionstr",type="string",help="newversionstr")
    parser.add_option("-v", "--vendor", dest="vendor",type="string",help="vendor string. For example MOT,LG")
    parser.add_option("-m", "--nospacemodel", dest="nospacemodel",type="string",help=" no space model for the model. For example Mini3v")    
    
    parser.add_option("-c", action="store_true", dest="scomo",help="plug in the scomo")
    parser.add_option("-a", action="store_true", dest="withapp",help="withapp in the target file")    
    
    (options, args) = parser.parse_args(args=argv)
    
    nospacemodel = rawsource = rawtarget = fssource  = fstarget = newversionstr = vendor = None
    scomo = False
    withapp = False
    
    if options.nospacemodel:
        nospacemodel = options.nospacemodel
        globalvar.MODELNAME_IN_FILE = nospacemodel
        
    if options.rawsource:
        rawsource = os.path.abspath(options.rawsource)       

    if options.rawtarget:
        rawtarget = os.path.abspath(options.rawtarget)       
        
    if options.fssource:    
        fssource = os.path.abspath(options.fssource)

    if options.fstarget:    
        fstarget = os.path.abspath(options.fstarget)
        
    if options.newversionstr:
        newversionstr = options.newversionstr
        
    if options.vendor:
        vendor = options.vendor
        
    if options.scomo:
        scomo = options.scomo
        
    if options.withapp:
        withapp = options.withapp

                        
    fs_diff.gen_fs_diff(fssource,fstarget,newversionstr,vendor,withapp)    
              
    if rawsource!= None:        
        kernel_diff.gen_kernel_diff(rawsource, rawtarget)
        upk_gen.upk_gen('%s-%s_raw_upgrade.bin'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE), None, '%s-%s_fs_upgrade.bin'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE), '%s-%s_upgrade.upk'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE))
        upk_gen.upk_gen('%s-%s_raw_degrade.bin'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE), None, '%s-%s_fs_degrade.bin'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE), '%s-%s_degrade.upk'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE))

    else:
        upk_gen.upk_gen(None, None, '%s-%s_fs_upgrade.bin'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE), '%s-%s_upgrade.upk'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE))
        upk_gen.upk_gen(None, None, '%s-%s_fs_degrade.bin'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE), '%s-%s_degrade.upk'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE))

 
    dn = datetime.datetime.now()
    dn_str = dn.strftime('%Y-%m-%d')   
    dn_str_long = dn.strftime('%Y-%m-%d-%H-%M-%S')
    upc_gen.upc_gen('%s-%s_upgrade.upk'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE),
                    globalvar.VENDOR,globalvar.MODEL,'%s_%s_%s_upgrade_%s'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE,globalvar.OLD_VERSION,dn_str),
                    globalvar.OLD_VERSION,globalvar.NEW_VERSION,
                    'borqs_%s_desc harold'%(globalvar.MODEL),
                    '%s-%s-%s-%s-%s_upgrade.upc'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE,globalvar.OLD_VERSION,globalvar.NEW_VERSION,dn_str))
    
    upc_gen.upc_gen('%s-%s_degrade.upk'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE),
                    globalvar.VENDOR,globalvar.MODEL,'%s_%s_%s_degrade_%s'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE,globalvar.NEW_VERSION,dn_str),
                    globalvar.NEW_VERSION,globalvar.OLD_VERSION,
                    'borqs_%s_desc harold'%(globalvar.MODEL),
                     '%s-%s-%s-%s-%s_degrade.upc'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE,globalvar.NEW_VERSION,globalvar.OLD_VERSION,dn_str))

    config = ConfigParser.ConfigParser()
    config.read('products.ini')
    globalvar.PLATFORM=config.get(globalvar.MODEL,'platform')


#Generate the cmcc_menu_update upc

    upc_gen.upc_gen('./CMCC_MENU_Update/%s/CMCCService.upk'%(globalvar.PLATFORM),
                    globalvar.VENDOR,globalvar.MODEL,'%s_%s_%s_menu_upgrade_%s'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE,globalvar.OLD_VERSION,dn_str),
                    globalvar.OLD_VERSION,globalvar.NEW_VERSION,
                    'borqs_%s_desc cmcc menu harold'%(globalvar.MODEL),
                    '%s-%s-%s_menu_upgrade.upc'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE,globalvar.OLD_VERSION))

 
#Generate the scomo files
    if scomo==True:
        #(infile,name,version,vendor,outfile):
        scomo_gen.scomo_gen('./SCOMO/%s/Sudoku1.0.apk'%(globalvar.PLATFORM),'Sudoku','1.0',globalvar.VENDOR,'%s-%s-Sudoku-1.0.pkg'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE))
        scomo_gen.scomo_gen('./SCOMO/%s/Sudoku1.1.apk'%(globalvar.PLATFORM),'Sudoku','1.1',globalvar.VENDOR,'%s-%s-Sudoku-1.1.pkg'%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE))
#Zip file the output file
    file = zipfile.ZipFile("%s_%s-%s-%s-%s.zip"%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE,globalvar.OLD_VERSION,globalvar.NEW_VERSION,dn_str_long), "w")

    for name in glob.glob("%s-*"%(globalvar.VENDOR)):
        file.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED)

        
#zip the input file also
    if rawsource:
        file.write(rawsource, os.path.basename(rawsource), zipfile.ZIP_DEFLATED)
    if rawtarget:
        file.write(rawtarget, os.path.basename(rawtarget), zipfile.ZIP_DEFLATED)
    if fssource:
        file.write(fssource, os.path.basename(fssource), zipfile.ZIP_DEFLATED)
    if fstarget:
        file.write(fstarget, os.path.basename(fstarget), zipfile.ZIP_DEFLATED)
        
    file.close()
    
    for name in glob.glob("%s-*"%(globalvar.VENDOR)):
        os.system("DEL %s"%(name))
if __name__ == "__main__":
    
    logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s  %(levelname)-8s %(message)s',
                    filename="dm.log",
                    datefmt="%m-%d %H:%M:%S",        
                    filemode='a')

    console=logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)

    globalvar.dmlogging = logging.getLogger('DM')

    
    
    main()
    